/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86186
 * Date: 2023-07-13
 * Time: 16:01
 */
public class PriorityQueue {
    public int[] elem;
    public int usedSize;

    public PriorityQueue(int[] array) {
        this.elem = new int[20];
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    /**
     * 建堆的时间复杂度：
     */
    public void createHeap() {
        for (int p = (usedSize - 1 - 1) / 2; p >= 0; p--) {
            shiftDown(p, usedSize);
        }
    }

    /**
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     *             向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root, int len) {
        int child = 2 * root + 1;
        while (child < len) {
            if (child + 1 < len && elem[child + 1] < elem[child]) {
                child++;
            }
            if (elem[child] < elem[root]) {
                swap(root, child);
            } else {
                break;
            }
            root = child;
            child = 2 * root + 1;
        }
    }

    private void swap(int a, int b) {
        int tmp = elem[a];
        elem[a] = elem[b];
        elem[b] = tmp;
    }


    /**
     * 入队：仍然要保持是大根堆
     *
     * @param val
     */
    public void push(int val) {
        elem[usedSize++] = val;
        shiftUp(usedSize-1);
    }

    private void shiftUp(int child) {
        int parent = (child-1) / 2;
        while(parent >= 0) {
            if(elem[child] < elem[parent]) {
                swap(child,parent);
            }else {
                break;
            }
            child = parent;
            parent = (child-1) / 2;
        }
    }
}
